package com.qf.smsplatform.strategy.impl;

import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.Strategy;
import com.qf.smsplatform.util.PushMessage2Queue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service(value = "router")
@Slf4j
public class RouterStrategy implements Strategy {

    @Autowired
    private PushMessage2Queue pushMessage2Queue;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public boolean strategy(StandardSubmit submit) {
        log.info("【策略模块-路由策略】 路由策略开始执行！！");
        //1. 判断submit中的gatewayID.
        int gatewayID = submit.getGatewayID();

        //2. 如果为0,记录日志,发送消息,返回false
        if(gatewayID == 0){
            log.info("【策略模块-路由策略】 路由策略失败, 没有指定的通道信息...");
            pushMessage2Queue.sendLogMessage(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            pushMessage2Queue.pushReportMessage(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            return false;
        }

        //3. 直接发送消息到MQ
        // 避免404,先创建出这个队列
        String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + gatewayID;
        amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
        rabbitTemplate.convertAndSend(queueName,submit);
        log.info("【策略模块-路由策略】 路由策略执行结束！！");
        return true;
    }
}
